package jianzhiOffer;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;

/**
 * @author : xwj
 * @date : 2021/9/30 15:16
 * @description : 输入一个链表的头节点，从尾到头反过来返回每个节点的值（用数组返回）。
 * @class : test03
 **/

public class test03 {

    public static class ListNode {
        int val;
        ListNode next;
        ListNode() {}
        ListNode(int val) { this.val = val; }
    }

    //1. 1 ms	38.9 MB
    /*
    *  将链表遍历，结果存入一个动态数组中，再将数组的值逆序付给int[]
    *  */
    public static int[] reversePrint(ListNode head) {
        ArrayList<Integer> res = new ArrayList<>();
        int len = 0;
        while (head != null) {
            res.add(head.val);
            head = head.next;
            len++;
        }
        int[] r = new int[len];
        for (int i = len - 1, j = 0; i >= 0; i--, j++) {
            r[j] = res.get(i);
        }
        return r;
    }

    //2. 0 ms	38.8 MB
    /*
    * 先求出链表长度，直接将值付给数组中的相应位置
    * */
    public static int[] reversePrint2(ListNode head) {
        ListNode p = head;
        int len = 0;
        while (p != null) {
            p = p.next;
            len++;
        }
        int[] r = new int[len];
        while (head != null) {
            r[len - 1] = head.val;
            head = head.next;
            len--;
        }
        return r;
    }

    public static void main(String[] args) {

        ListNode tail = new ListNode(2);
        ListNode tmp = new ListNode(3);
        ListNode head = new ListNode(1);
        head.next = tmp;
        tmp.next = tail;

        int[] r = reversePrint(head);
        for (int i = 0; i < r.length; i++) {
            System.out.print(r[i] + " ");
        }

    }

}
